import { mapGetters, mapMutations, mapActions } from "vuex"
import { playMode } from 'common/js/config'
import { shuffle } from 'common/js/util'

export const playlistMixin = {
  computed: {
    ...mapGetters([
      'playlist'
    ])
  },

  mounted() {
    this.handlePlaylist(this.playlist)
  },

  activated() {
    this.handlePlaylist(this.playlist)
  },

  watch: {
    playlist(newVal) {
      this.handlePlaylist(newVal)
    }
  },

  methods: {
    handlePlaylist() {
      throw new Error('component must implement handlePlayList method')
    },

    
  }
}


// player和play-list组件公用的属性和方法
export const playerMixin = {
  computed: {
    // 播放模式的样式
    iconMode() {
      return this.mode === playMode.sequence ? 'icon-sequence' : this.mode === playMode.loop ? 'icon-loop' : 'icon-random'
    },

    ...mapGetters([
      'sequenceList',
      'currentSong',
      'playlist',
      'mode',
      'favoriteList'
    ])
  },
  methods: {
    // 改变播放模式操作
    changeMode() {
      const mode = (this.mode + 1) % 3 
      this.setPlayMode(mode)

      let list = null
      if (mode === playMode.random) {
        list = shuffle(this.sequenceList)
      } else {
        list = this.sequenceList
      }
      this.resetCurrentIndex(list)
      this.setPlayList(list)
    },

    resetCurrentIndex(list) {
      let index = list.findIndex((item) => {
        return item.id === this.currentSong.id
      })
      this.setCurrentIndex(index)
    },

    // 返回收藏歌曲的样式
    getFavoriteIcon(song) {
      if (this.isFavorite(song)) {
        return 'icon-favorite'
      }
      return 'icon-not-favorite'
    },

    // 切换收藏
    toggleFavorite(song) {
      // 判断是否在收藏列表里，有则从收藏列表删除
      if (this.isFavorite(song)) {
        this.deleteFavoriteList(song)
      } else {
        this.saveFavoriteList(song)
      }
    },

    // 判断是否在favoritelist里面
    isFavorite(song) {
      const index = this.favoriteList.findIndex((item) => {
        return item.id === song.id
      })
      // 如果大于-1 证明在favoritelist里面
      return index > -1
    },

    ...mapMutations({
      setPlayingState: 'SET_PLAYING_STATE',
      setCurrentIndex: 'SET_CURRENT_INDEX',
      setPlayMode: 'SET_PLAY_MODE',
      setPlayList: 'SET_PLAYLIST'
    }),
    
    ...mapActions([
      'saveFavoriteList',
      'deleteFavoriteList'
    ])
  }
}


// 搜索组件公用的数据和方法
export const SearchMixin = {
  data() {
    return {
      query: '',

      refreshDelay: 100
    }
  },

  computed: {
    ...mapGetters([
      'searchHistory'
    ])
  },
  methods: {

    // 保存搜索结果
    saveSearch() {
      this.saveSearchHistory(this.query)
    },

    // 手机端上滚动会取消键盘显示
    blurInput() {
      this.$refs.searchbox.blur()
    },

    // 监听搜索关键词的改变
    onQueryChange(newQuery) {
      this.query = newQuery
    },

    // 设置搜索栏的关键词
    setQuery(query) {
      this.$refs.searchbox.addQuery(query)
    },

    ...mapActions([
      'saveSearchHistory',
      'deleteSearchHistory',
    ])
  }
}